package com.tpsix.controller;

import com.tpsix.domain.SysDept;
import com.tpsix.service.SysDeptService;
import com.tpsix.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(value = "depts", tags = "系统部门资源")
@RestController
@RequestMapping("depts")
@AllArgsConstructor
public class SysDeptResource {

    private final SysDeptService sysDeptService;

    /**
     * 获取部门树
     * @return {@link R}
     */
    @ApiOperation(value = "获取部门树")
    @GetMapping("tree")
    @PreAuthorize("hasAuthority('sys:dept:view')")
    public R<List<SysDept>> tree() {
        List<SysDept> depts = sysDeptService.deptTree();
        return R.ok(depts);
    }

    @GetMapping("{id:\\d+}")
    @ApiOperation(value = "部门节点信息")
    @PreAuthorize("hasAuthority('sys:dept:view')")
    public R<SysDept> getDeptInfoByDeptId(@PathVariable int id) {
        SysDept sysDept = sysDeptService.getById(id);
//        SysDept sysDeptParentName = sysDeptService.getById(sysDept.getParentId());
//        sysDept.setParentName(sysDeptParentName.getName());
        return R.ok(sysDept);
    }

    @PostMapping
    @ApiOperation("新增部门")
    @PreAuthorize("hasAuthority('sys:dept:add')")
    public R<Void> add(@RequestBody SysDept sysDept) {
        boolean update  = sysDeptService.addOrUpdate(sysDept,"add");
        System.out.println(String.format("update: %b", update));
        return R.ok();
    }

    //upDeptInfo
    @PutMapping
    @ApiOperation("修改部门")
    @PreAuthorize("hasAuthority('sys:dept:update')")
    public R<Void> put(@RequestBody SysDept sysDept) {
        boolean update  = sysDeptService.addOrUpdate(sysDept,"upd");
        System.out.println(String.format("update: %b", update));
        return R.ok();
    }
    @ApiOperation("删除部门")
    @DeleteMapping("{id:\\d+}")
    @PreAuthorize("hasAuthority('sys:dept:delete')")
    public R<Void> delete(@PathVariable int id) {
        boolean remove  = sysDeptService.removeById(id);
        System.out.println(String.format("remove: %b", remove));
        return R.ok();
    }
}
